package com.lx.tomcat.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class BioServer extends BaseServer<Socket>{



    public static void main(String[]args) throws IOException {
        new BioServer().accept();
    }

    @Override
    public void accept() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true){
            Socket accept = serverSocket.accept();
            request(accept);
        }
    }

    @Override
    protected void processor(Socket socket) throws IOException {
        Request request = new Request(socket);
        System.out.println(request);
        Response response = new Response(socket);
        String responseHeader="HTTP/1.1 200 \r\nContent-Type: text/html; charset=utf-8\r\n\r\n";
        response.write(responseHeader);
        response.write("调用成功!");
        response.close();
    }

    public static class Request{
        public String url;
        public Map<String,String> parameter;
        public String body;
        public Request(Socket socket) throws IOException {
            StringBuilder builder = new StringBuilder();
            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            char[] charBuf = new char[1024];
            int mark;
            while ((mark = isr.read(charBuf)) != -1) {
                builder.append(charBuf, 0, mark);
                if (mark < charBuf.length) break;
            }
            if ("".equals(builder.toString())) return;
            System.out.println(builder);
            String line = builder.substring(0, builder.indexOf("\r\n"));
            url = URLDecoder.decode(line.split("\\s")[1]);
            if ("/".equals(url)){
                url = "/index.html";
            }else if (url.indexOf("?")!=-1){
                url = url.substring(0,url.indexOf("?"));
            }
            body = builder.substring(builder.indexOf("\r\n\r\n")+4);
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", parameter=" + parameter +
                    ", body='" + body + '\'' +
                    '}';
        }
    }

    public static class Response{
        private Socket socket;
        public Response(Socket socket) {
            this.socket = socket;
        }
        public void write(byte[] bytes) throws IOException {
            socket.getOutputStream().write(bytes);
        }
        public void write(String line) throws IOException {
            socket.getOutputStream().write(line.getBytes(StandardCharsets.UTF_8));
        }
        public void close() throws IOException {
            socket.getOutputStream().close();
        }
    }
}
